import style from '../assets/css/Order.module.css';
import { NavBar, Dialog, Checkbox, Toast,CheckList,Selector,Form ,Input} from 'antd-mobile/2x';
import { useHistory, useLocation } from 'react-router-dom';
import { useEffect, useState } from 'react';
import {useSelector,useDispatch} from 'react-redux'
// import dayjs from 'dayjs'
import $api from '../api';
import { setPreOrderInfo } from '../store/reducer';

const Order = () => {

    const history = useHistory();

    const location = useLocation(); 

    let id = new URLSearchParams(location.search).get('id'); //获取id
    let date = new URLSearchParams(location.search).get('date')

    const [flightInfo, setFlightInfo] = useState({}); //航班信息
    const [linkMan, setlinkMan] = useState([]); //乘车人列表
    const [startStation, setStartStation] = useState(''); //选择的出发站点
    const [arriveStation, setArriveStation] = useState(''); 
    const [who, setWho] = useState([]); //乘车人
    const [phone, setPhone] = useState(''); //联系电话


    // 弹出框
    useEffect(() => {
        Dialog.alert({
            content: (
                <>
                    根据交通管理部门规定，定制包车服务必须为一人一座(包含儿童及手抱婴儿)，请乘客按照实际乘车人数购票;符合1.5米以下的儿童可在乘车后向客服申请儿童票,儿童票价为原票价(非优惠价)的一半;所有未购票乘客，本平台将拒绝乘车，为避免您的行程受阻，敬请知悉，多谢合作。
                    <div>
                        <Checkbox
                            style={{
                                '--icon-size': '18px',
                                '--font-size': '14px',
                                '--gap': '6px',
                            }}
                        >
                            不再提示
                        </Checkbox>
                    </div>
                </>
                
            ),
            onConfirm: () => {
                console.log('Confirmed')
            },
        })
    }, []);
    
    useEffect(() => {
        if (!id) {
            Toast.show({
                content: '获取参数有误',
            });
            return setTimeout(() => {
                history.goBack();
            }, 1000);
        };
    }, []);
    
    useEffect(() => {
        getFlightInfo(); //获取路线信息
        getLinkMan(); //获取联系人信息
    }, []);

    //根据传入的id获取线路信息 
    const getFlightInfo = async () => {
        const res = await $api.post('/flight/getOne', { id });
        const { data, success } = res.data;
        // console.log(data);
        if (!success) return Toast.show({ content: '抱歉出错了' });
        setFlightInfo(data);
    };

    // 获取全部乘车人信息
    const getLinkMan = async () => {
        const res = await $api.post('/linkMan/getAll');
        const { data, success } = res.data;
        if (!success) return Toast.show({ content: '抱歉出错了' });
        setlinkMan(data);
    };

    // 获取redux中的起点城市和到达城市
    const st = useSelector(state => state);//获取redux的state
    const dispatch = useDispatch();//redux分发器

    // 下单
    const handleOrder = async() => {
        //需要传入的值 phone,startCity,arriveCity,startStationId,arriveStationId, orderDate,linkMan,flightNum

        const { startCity, arriveCity } = st;        //起始点城市
        const startStationId = startStation;         //出发站点id
        const arriveStationId = arriveStation;       //到达站点id
        const orderDate =new Date().getFullYear()+'-'+date+'  '+flightInfo.startTime; //订单乘车时间
        const flightNum = flightInfo.flightNum;        //线路编号
        const linkMan = who;//乘车人

        if (/^1(3456789)\d{9}$/.test(phone)) return Toast.show({ content: '请填写正确的手机号码' });
        if (linkMan.length === 0) return Toast.show({ content: '请选择乘车人' });
        if (!startStationId) return Toast.show({ content:'请选择上车站点' });
        if (!arriveStationId) return Toast.show({ content:'请选择下车站点' });

        const postData = {
            phone,
            startCity,
            arriveCity,
            startStationId,
            arriveStationId,
            orderDate: new Date(orderDate),
            flightNum,
            linkMan,
        };
        const _res = await $api.post('order/preOrder', postData);
        const { success, data } = _res.data;
        console.log(data)
        if (!success) return Toast.show({ content: '下单失败' });
        Toast.show({ content: '下单成功请立即支付' });

        dispatch(setPreOrderInfo(postData));

        history.push('/OrderDetail?id='+data)
    }

    return(
        <div className={style.main}>
            <NavBar onBack={() => history.goBack()}>订单信息</NavBar>
            <div className={style.ct}>

                {/* 车票信息 */}
                <div className={style.fbox}>
                    {/* 时间 票价 */}
                    <div className={style.ft}>
                        <div className={style.ftime}>{date} {flightInfo.startTime}</div>
                    </div>
                    {/* 站点 */}
                    <div className={style.fstation}>
                        <div className={style.fs}>
                            {flightInfo.startCity}
                        </div>
                        <div>
                            {flightInfo.startStations && <Selector
                                onChange={val =>
                                    setStartStation(val[0])
                                }
                                options={flightInfo.startStations.map(item => ( 
                                {
                                    label: item,
                                    value: item,
                                }
                                ))}
                            />}
                        </div>
                        <div className={style.fe}>
                            {flightInfo.arriveCity}
                        </div>
                        <div>
                            {flightInfo.arriveStations && <Selector
                                onChange={val =>
                                    setArriveStation(val[0])
                                }
                                options={flightInfo.arriveStations.map(item => ( 
                                {
                                    label: item,
                                    value: item,
                                }
                                ))}
                            />}
                        </div>
                    </div>
                </div>

                {/* 联系电话 */}
                <div className={style.phone}>
                    <Form.Item layout='horizontal' name='phone' label='联系电话' rules={[{ required: true,message: '联系电话不能为空' }]}>
                        <Input placeholder='请输入电话号码' onChange={val => setPhone(val)} /> 
                        {/* 得到输入的phone */}
                    </Form.Item> 
                </div>
               

                {/* 添加乘车人 */}
                <div className={style.ccr}>
                    <div className={style.addccr}>请选择乘车人</div>
                    <div className={style.rideZone}>
                        {/* 遍历出选中的乘车人 */}
                         { who.map(item=>(
                            <div className={style.rideManBox} key={item.realName}>
                                {item.realName}
                             </div>
                        ))  }
                        
                        <div className={style.addRide} onClick={()=>history.push('/AddClient')}>
                            新增
                        </div>
                    </div>
                    <div className={style.rideManList}>
                        {/* 添加的乘车人列表 */}
                        <CheckList multiple onChange={val=>setWho(val)}>
                            {/* multiple选中多个 */}
                            {linkMan.map(item => (
                                // value 选中项
                                <CheckList.Item value={item} key={item._id}>
                                    <div className={style.rideMan} key={item.id+item}>
                                    <div> {item.realName} </div>
                                    <div>  { item.idNumber }</div>
                                    <div>  { flightInfo.ticketPrice/100 }元 </div>
                                    </div>
                                </CheckList.Item>
                                ))
                            }
                        </CheckList>
                       
                        
                    </div>
                </div>
                
                {/* 温馨提示 */}
                <div className={style.readme}>
                    温馨提示区域
                </div>
            </div>
            <div className={style.orderBtn}>
                <div className={style.orderInfo}>
                    {/* 乘车人数*票价/100 */}
                    <div>订单金额：<span>{ who.length*flightInfo.ticketPrice/100}元</span></div>
                    <div>明细</div>
                </div>
                <div className={style.pay} onClick={handleOrder}>下单并支付</div>
            </div>
        </div>
    )
}
export default Order